package com.cjj.springsecurity.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.cjj.common.entity.po.master.CPermission;
import com.cjj.common.entity.po.master.CRole;
import com.cjj.common.entity.po.master.CUser;
import com.cjj.common.facade.UserFacadeService;
import com.cjj.common.framework.exception.SecurityException;
import com.cjj.common.utils.StringUtils;
import com.cjj.springsecurity.entity.MyGrantedAuthorityUrlMethod;
import com.cjj.springsecurity.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author by BrownC_
 * @date 2021/12/21 11:29:08
 * @email ccc-ju@outlook.com
 */
@Service
@Slf4j
public class UserServiceDetails implements UserDetailsService {

    @Autowired
    private UserFacadeService userFacadeService;

    /**
     * 用户登录时自动调用
     * @param username username / mobile / email
     * @return UserDetails
     * @throws UsernameNotFoundException 用户未找到
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        CUser user = Optional.ofNullable(userFacadeService.loadUserByUserName(username)).orElseThrow(() -> new UsernameNotFoundException("用户名或密码错误!"));
        // 获取角色对应的接口权限
        List<CRole> roles = userFacadeService.getRoleInfoByUid(user.getUid());
        if(ObjectUtil.isEmpty(roles)){
            log.error("用户[" + user.getUsername() + "], 用户角色信息未找到, 请开发人员协助排查");
            throw new SecurityException(SecurityException.Status.DEFAULT_ERROR);
        }
        List<CPermission> permissions = userFacadeService.getPermissionsByRoleId(roles.stream().map(CRole::getId).collect(Collectors.toList()));
        if(ObjectUtil.isEmpty(permissions)){
            log.error("用户[" + user.getUsername() + "], 用户权限信息未找到, 请开发人员协助排查");
            throw new SecurityException(SecurityException.Status.DEFAULT_ERROR);
        }
        List<MyGrantedAuthorityUrlMethod> grantedAuthorityUrlMethods = permissions.stream().filter(e -> StringUtils.isNotEmpty(e.getMethod())).map(e -> {
            return MyGrantedAuthorityUrlMethod.builder().url(e.getUrl()).method(e.getMethod()).build();
        }).collect(Collectors.toList());
        User securityUser = User.builder()
                .id(user.getUid())
                .nickName(user.getNickname())
                .userName(user.getUsername())
                .mobile(user.getMobile())
                .email(user.getEmail())
                .birthday(user.getBirthday())
                .status(user.getStatus())
                .roles(roles)
                .permissions(permissions)
                .grantedAuthorityUrlMethods(grantedAuthorityUrlMethods)
                .build();
        log.info("securityUser------>" + JSON.toJSONString(securityUser));
        return securityUser;
    }
}
